import router from '@/router';
import {  useUserStore } from '@/store';
import { getPermissionStore } from '@/store';
router.beforeEach(async (to,from,next)=>{
    // console.log(to,from,next)
    const userStore = useUserStore();
    const permissionStore = getPermissionStore();
    const { whiteListRouters } = permissionStore;
    if (userStore.token) {
        await userStore.getUserInfo();
        if (to.path === '/login') {
          next();
          return;
        }
        try {
          if (router.hasRoute(to.name)) {
            next();
          } else {
            next(`/`);
          }
        } catch (error) {
          next({
            path: '/login',
            query: { redirect: encodeURIComponent(to.fullPath) },
          });
        }
    } else {
        if (whiteListRouters.includes(to.path)) {
            next();
            return;
        }
        next({
            path: '/login',
            query: { redirect: encodeURIComponent(to.fullPath) },
        });
    }
})

router.afterEach((to) => {
  if (to.path === '/login') {
    const userStore = useUserStore();
    userStore.logout();
  }
});